import axios, { type AxiosResponse } from 'axios'

// 统一响应接口
interface ApiResponse<T = any> {
  code: number
  message: string
  data: T
  traceId: string
}

export interface ApiErrorNormalized extends Error {
  status?: number
  code?: number | string
  traceId?: string
  details?: any
}

export const getErrorMessage = (error: any): string => {
  if (!error) return '未知错误'
  if (typeof error === 'string') return error
  if (error.message && typeof error.message === 'string') return error.message
  const data = error.response?.data || error.data
  return (
    data?.message || data?.msg || data?.error || data?.errors?.[0]?.message || '请求失败'
  )
}

const normalizeError = (error: any): ApiErrorNormalized => {
  const e: ApiErrorNormalized = new Error(getErrorMessage(error))
  e.name = 'ApiError'
  e.status = error?.response?.status
  const payload = error?.response?.data || error?.data
  e.code = payload?.code
  e.traceId = payload?.traceId
  e.details = payload
  return e
}

// 创建axios实例
const http = axios.create({
  baseURL: '/api',
  timeout: 600000, // 10分钟超时，适合2GB视频上传
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 添加token到请求头
    const token = localStorage.getItem('access_token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    const { data } = response
    console.log('API Response:', data)
    // 支持两种返回：包装({code,message,data}) 或 直出业务对象
    if (data && typeof data === 'object' && 'code' in data) {
      if ((data as any).code === 0) return (data as any).data
      const err = normalizeError({ response: { data } })
      return Promise.reject(err)
    }
    return data as any
  },
  async (error) => {
    console.error('Request Error:', error)
    // 网络错误/超时
    if (error.code === 'ECONNABORTED') {
      return Promise.reject(new Error('请求超时，请稍后重试'))
    }
    if (!error.response) {
      return Promise.reject(new Error('网络连接失败，请检查后端服务或网络'))
    }
    // 401 尝试刷新
    if (error.response?.status === 401) {
      console.log('Token可能过期，尝试刷新...')
      const refreshToken = localStorage.getItem('refresh_token')
      if (refreshToken) {
        try {
          const refreshResponse = await axios.post('/api/v1/auth/refresh', { refreshToken })
          if (refreshResponse.data && refreshResponse.data.code === 0) {
            const newAccessToken = refreshResponse.data.data.accessToken
            localStorage.setItem('access_token', newAccessToken)
            const originalRequest = error.config
            originalRequest.headers.Authorization = `Bearer ${newAccessToken}`
            return http.request(originalRequest)
          }
        } catch (refreshError) {
          console.error('Token刷新失败:', refreshError)
          localStorage.removeItem('access_token')
          localStorage.removeItem('refresh_token')
          window.location.href = '/login'
          return Promise.reject(normalizeError(refreshError))
        }
      } else {
        localStorage.removeItem('access_token')
        localStorage.removeItem('refresh_token')
        window.location.href = '/login'
      }
    }
    return Promise.reject(normalizeError(error))
  }
)

export default http
